TypeScript における enum の reverse mapping
TypeScript でには enum がある。この enum に対して reverse mapping をしたいとする。
code:typescript
enum Color {
Red = 'RED',
Green = 'GREEN'
}
const colorStr = 'RED'
// colorStr から、同一の値をもつ Color があればそれをひっぱってきたい...
console.log(ColorcolorStr); // undefined
String の reverse mapping は、現状 TypeScript の 仕様として 実装されていない。
If we provided the reverse map automatically (which, by the way, is not necessarily non-ambiguous!), then you'd have no way to distinguish keys from values unless there was a completely separate object created at runtime. It is trivial to write a function that constructs the reverse map if you want it; our goal is to emit as little code as possible so it makes sense to just emit the data you need (to keep code size down) and let you construct the reverse map on an as-needed basis.
https://github.com/Microsoft/TypeScript/issues/21935
欲しいのであれば、自分で reverse mapping 用の関数を実装する必要がある。